package com.wechat.service.storage;

import java.io.File;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import com.swak.App;
import com.swak.codec.Digests;
import com.swak.utils.StringUtils;
import com.wechat.Cons;
import com.wechat.service.StorageService;

@Service("SubjectHeadimgStorageService")
public class SubjectHeadimgStorageService extends SubjectStorageService implements InitializingBean {

	private File path;

	public SubjectHeadimgStorageService() {
	}

	public SubjectHeadimgStorageService(StorageService storageService, App app) {
		super(storageService, app);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.path = new File(this.getStoragePath(), Cons.Headimg_Name);
		if (!this.path.exists()) {
			this.path.mkdirs();
		}
	}

	/**
	 * 保存头像
	 * 
	 * @param image
	 * @return
	 */
	public String save(byte[] image) {
		String imageId = Digests.digest(image);
		String imageName = this.genFileIDByName(imageId) + ".dat";
		String path = StringUtils.format("/%s/%s/%s", Cons.Headimg_Name, this.genFilePrefDirName(imageName), imageName);
		File saved = this.storageService.writeIfAbsent(path, image);
		return StringUtils.format("/%s/%s/%s", Cons.Headimg_Name, this.genFilePrefDirName(saved.getName()),
				saved.getName());
	}

	/**
	 * 读取头像
	 * 
	 * @param path
	 * @return
	 */
	public File open(String path) {
		return this.storageService.open(path);
	}
}
